package com.wsg.lightaccounting.Fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.wsg.lightaccounting.Model.RecordManager;
import com.wsg.lightaccounting.Model.TypeSum;
import com.wsg.lightaccounting.R;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link CircularFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link CircularFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CircularFragment extends Fragment {
    private PieChart circular_chart_expendituer,circular_chart_income;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public static String UPDATEUI_CIRCULAR_FRAGMENT = "update UI in record_fragment";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(UPDATEUI_CIRCULAR_FRAGMENT)){
                updateUI();
            }
        }
    };

    public CircularFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CircularFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CircularFragment newInstance(String param1, String param2) {
        CircularFragment fragment = new CircularFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATEUI_CIRCULAR_FRAGMENT);
        getActivity().registerReceiver(broadcastReceiver,intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_circular, container, false);
        initView(view);
        return view;
    }
    private void initView(View view){
        circular_chart_expendituer = (PieChart) view.findViewById(R.id.circular_chart_expenditure);
        circular_chart_income = (PieChart) view.findViewById(R.id.circular_chart_income);
        showChart(circular_chart_expendituer,getExpenditureTypeSum());
        showChart(circular_chart_income,getIncomeTypeSum());
    }
    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }
    public void updateUI(){
        circular_chart_expendituer.setData(getExpenditureTypeSum());
        circular_chart_income.setData(getIncomeTypeSum());
        circular_chart_expendituer.notifyDataSetChanged();
        circular_chart_income.notifyDataSetChanged();
        circular_chart_expendituer.animateXY(2000,2000);
        circular_chart_income.animateXY(2000,2000);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        updateUI();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    private void showChart(PieChart pieChart, PieData pieData) {
        pieChart.setHoleColorTransparent(true);
        pieChart.setHoleRadius(60f);  //半径
        pieChart.setHoleRadius(0);  //实心圆
        pieChart.setDrawCenterText(false);  //饼状图中间可以添加文字
        pieChart.setDrawHoleEnabled(true);
        pieChart.setRotationAngle(0); // 初始旋转角度
        pieChart.setRotationEnabled(true);
        pieChart.setUsePercentValues(true);  //显示成百分比
        //设置数据
        pieChart.setNoDataText("没有数据");
        pieChart.setData(pieData);
        Legend mLegend = pieChart.getLegend();  //设置比例图
        mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);  //最右边显示
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);
        pieChart.animateXY(1000, 1000);  //设置动画
    }

    private PieData getExpenditureTypeSum(){
        List<TypeSum> list = RecordManager.getRecordManager(getActivity()).getExpenditrueTypeSum();
        ArrayList<Entry> yValues = new ArrayList<Entry>();
        ArrayList<String> xValues = new ArrayList<String>();  //xVals用来表示每个饼块上的内容
        for (int i = 0; i < list.size(); i++) {
            xValues.add(list.get(i).getTypename());
            yValues.add(new Entry(list.get(i).getSum(),i));
        }
        PieDataSet pieDataSet = new PieDataSet(yValues, "支出比例");  //*显示在比例图上;
        pieDataSet.setSliceSpace(0f);

        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
//
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        pieDataSet.setColors(colors);

        PieData pieData = new PieData(xValues, pieDataSet);
        return pieData;
    }

    private PieData getIncomeTypeSum(){
        List<TypeSum> list = RecordManager.getRecordManager(getActivity()).getIncomeTypeSum();
        ArrayList<Entry> yValues = new ArrayList<Entry>();
        ArrayList<String> xValues = new ArrayList<String>();  //xVals用来表示每个饼块上的内容
        for (int i = 0; i < list.size(); i++) {
            xValues.add(list.get(i).getTypename());
            yValues.add(new Entry(list.get(i).getSum(),i));
        }
        PieDataSet pieDataSet = new PieDataSet(yValues, "收入比例");  //*显示在比例图上;
        pieDataSet.setSliceSpace(0f);

        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.JOYFUL_COLORS)
            colors.add(c);
//
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);

        for (int c : ColorTemplate.LIBERTY_COLORS)
            colors.add(c);

        pieDataSet.setColors(colors);

        PieData pieData = new PieData(xValues, pieDataSet);
        return pieData;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
